package com.luo.sc.oidc.authserver.handler.login;

import com.luo.sc.oidc.authserver.config.Oauth2ServerProps;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.savedrequest.RequestCache;

/**
 * 通用登录 - Security配置适配器
 *
 * @author luohq
 * @version 1.0.0
 * @date 2022-03-03、
 */
public class UniLoginAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final UniLoginUserDetailsService uniLoginUserDetailsService;
    private final Oauth2ServerProps oauth2ServerProps;
    private final RequestCache requestCache;

    public UniLoginAuthenticationSecurityConfig(Oauth2ServerProps oauth2ServerProps, UniLoginUserDetailsService uniLoginUserDetailsService, RequestCache requestCache) {
        this.uniLoginUserDetailsService = uniLoginUserDetailsService;
        this.oauth2ServerProps = oauth2ServerProps;
        this.requestCache = requestCache;
    }

    @Override
    public void configure(HttpSecurity http) {

        //认证过滤器
        UniLoginAuthenticationProcessingFilter uniLoginAuthenticationProcessingFilter = new UniLoginAuthenticationProcessingFilter(
                this.oauth2ServerProps.getLoginProcessingUrl(),
                http.getSharedObject(AuthenticationManager.class)
        );

        //自定义登录成功、失败处理器（支持Ajax Json响应结果）
        uniLoginAuthenticationProcessingFilter.setAuthenticationSuccessHandler(new UniLoginRespJsonAuthenticationSuccessHandler(this.requestCache));
        uniLoginAuthenticationProcessingFilter.setAuthenticationFailureHandler(new UniLoginRespJsonAuthenticationFailureHandler());

        //认证处理器
        UniLoginAuthenticationProvider uniLoginAuthenticationProvider = new UniLoginAuthenticationProvider(this.uniLoginUserDetailsService);

        //security配置
        http.authenticationProvider(uniLoginAuthenticationProvider)
                .addFilterBefore(uniLoginAuthenticationProcessingFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
